# coding:utf-8
__author__ = 'wangxiang'

import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
import requests
import json
from common.redis_control import RedisHandler
from base_test_case import BaseTestCase
from utils.logger import Logger

logger = Logger()


class HttpHandle(BaseTestCase):

    def __init__(self):
        self.http = requests.session()
        self.headers = {"Content-Type": "application/json;charset=UTF-8", "clientcode": "z1MQ4BdfJuYbp0oQ"}
        self.login_address = None
        self.result = None

    def login(self, charset_UTF8=True):
        self.headers = {"clientcode": "z1MQ4BdfJuYbp0oQ",
                        "Content-Type": "application/json{0}".format(";charset=UTF-8" if charset_UTF8 else '')}
        self.http = requests.session()
        self.login_address = self.read("Api", "url") + "/api-ocp/ocp-user/login/openApi/common"

        params = {
            "identifier": self.read("Api", "user_phone"),
            "password": self.read("Api", "user_password")
        }
        req = self.post(self.login_address, data=params, headers=self.headers)
        self.result = json.loads(req.text)

        if self.result['code'] == 0 and self.result['message'] == "成功":
            logger.info("登陆成功")
            self.token = self.result['data']["accessToken"]
        elif self.result["message"] == "检测到您账号异地登录，请使用验证码！":
            logger.info("异地登录需要发送验证码")

            login_code_params = {"codeType": "LOGIN", "phone": self.read("Api", "user_phone")}
            # ocp-test.orangecds.com
            self.post(
                self.read("Api", "url") + "/api-ocp/ocp-message/messageSmsSend/openApi/sendCode",
                data=login_code_params, headers=self.headers)
            login_num = RedisHandler().get_key(
                "ocp_message:sms:LOGIN:{}".format(self.read("Api", "user_phone"))).replace('"', "")
            # 通过验证码登录
            login_params = {
                "identifier": self.read("Api", "user_phone"),
                "code": login_num
            }
            code_req = self.post(self.login_address, data=login_params, headers=self.headers)

            self.token = json.loads(code_req.text)['data']["accessToken"]
        else:
            logger.error("Login failed! {0}".format(self.result['msg']))

    def post(self, url, data=None, convert_to_json=True, **kwargs):
        try:
            if convert_to_json:
                # 转为json
                data = json.dumps(data, ensure_ascii=False).encode('utf-8')
            if "headers" not in kwargs:
                header = {"Content-Type": "application/json;charset=UTF-8", "accessToken": self.token,
                          "clientcode": "z1MQ4BdfJuYbp0oQ"}
                kwargs['headers'] = header
            logger.info(kwargs)
            res = self.http.post(url, data=data, **kwargs)

        except Exception as err:
            logger.error(err)
            assert False
        if res.status_code == 200 or res.status_code == 201:
            response_time = res.elapsed.total_seconds()

            logger.info('发送post请求: %s  响应时间: %s  服务器返回: %s data: %s  ' %
                        (res.url, response_time, res.status_code, data))
        else:
            logger.error('发送post请求: %s 请求参数: %s 请求头: %s 服务器返回: %s\n返回内容:\n%s' %
                         (res.url, data, self.headers, res.status_code, res.content.decode('utf-8', 'ignore')))
            assert False

        return res
